package com.mooc.controller;

import com.mooc.bean.Demo;
import com.mooc.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private DemoService demoService;

    @RequestMapping("/hello/{id}")
    @ResponseBody
    public String hello(@PathVariable(value = "id") Long id) {
        return Optional.ofNullable(demoService.getDemoById(id)).map(Demo::toString).orElse("empty String");
    }



	@RequestMapping(value = "/submit", method = RequestMethod.GET)
	public String submit(RedirectAttributes attr, HttpServletRequest request) throws IOException {
		((FlashMap)((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes()))
				.getRequest()
				.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE))
				.put("name ", "张三丰");
		attr.addFlashAttribute("ordersId", "xxx");
		attr.addAttribute("local","zh-cn");

		FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
		outputFlashMap.put("author","sanmao");
		return "redirect:showorders";
	}

	@RequestMapping(value = "/showorders", method = RequestMethod.GET)
	public String showOrders(Model model) throws IOException {
		System.out.println(model.asMap());
		return "index";
	}

}
